package com.cloud.yangfeiself.util;

import io.jsonwebtoken.*;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.concurrent.TimeUnit;


@Component
@NoArgsConstructor
@RefreshScope
@Data
public class JwtUtil {

    @Value("${jwt.secret}")
    private String secret;


    @PostConstruct
    public void setSecret1() {
        System.out.println("-------------华丽的分割线---------------");
    }


/*    private static String secret; //静态域spring注入，动态配置刷新不了静态属性
    @Value("${jwt.secret}")
    public void setSecret2(String secret){
        JwtUtil.secret= secret;
    }*/

    public String generateToken(String userId, int exp, TimeUnit unit) {
        return Jwts.builder()
                .setSubject(userId)
                .setExpiration(new Date(System.currentTimeMillis() + unit.toMillis(exp)))
                .signWith(SignatureAlgorithm.HS512, secret).compact();

    }

    public String generateToken(String userId) {
        return generateToken(userId, 1,TimeUnit.HOURS);

    }


    public String refreshToken() {
        return null;
    }

    public String checkToken(String token) {
        Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        return claims.getSubject();
    }

}
